import React, { useEffect, useState } from 'react';
import { Table, Button, Space, TablePaginationConfig, Input, Upload, Pagination, Modal, Form, Select, notification, } from 'antd'
import "../../../styles/Custom_index.scss"

import { custom_search, custom_del, custom_delmany, custom_changeleader } from "../../../utils/api"
import type { ColumnsType } from 'antd/es/table'
import { DeleteOutlined } from "@ant-design/icons"
const { Search } = Input;
interface Props {

}
interface DataType {
    name: string;
    phone: string;
    email: string
    address: string;
    person: string;
    time: string
    key: string;
}

function Custom_index(props: Props) {
    var [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 10, total: 50 })
    var [data, setData] = useState([])
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    var [loading, setLoading] = useState(false);
    var [isModalOpen1, setIsModalOpen1] = useState(false)


    //使用from中的userfrom()方法，通过from来绑定要操作的from表单
    const [form] = Form.useForm()
    //决定了每一列渲染什么数据
    const columns: ColumnsType<DataType> = [

        {
            title: '姓名',
            dataIndex: 'name',
            key: 1

        },
        {
            title: '手机号',
            dataIndex: 'phone',
        },
        {
            title: '邮箱',
            dataIndex: 'email',
        },
        {
            title: '地址',
            dataIndex: 'address',
        },
        {
            title: '负责人',
            dataIndex: 'leader',
            key: 'leader'
        },
        {
            title: '呼入时间',
            dataIndex: 'time',
            key: 'time'
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <>
                    <i className='iconfont icon-delete' onClick={() => { del(record) }}><DeleteOutlined style={{ color: "red", cursor: "pointer" }} /></i>
                </>
            ),
        },
    ];

    //引入生命周期
    useEffect(() => {
        //请求客户列表
        custom_search({ searchKey: '', page: 1, count: 10 }).then((res) => {
            setData(res.data.list)//保存客户列表
            setPagination({ current: 1, pageSize: 10, total: res.data.total }) //保存总数
        })
    }, [])


    //显示 弹框 
    const showModel1 = () => {
        setIsModalOpen1(true);
    };
    //隐藏 弹框 新增 + 编辑
    const handleCancel1 = () => {
        setIsModalOpen1(false);
    };


    //批量更新客户leader
    var editleader = () => {
        showModel1()

    }
    //表单验证通过 执行
    const onFinish = (values: any) => {
        custom_changeleader({ leader: values.leader, keys: selectedRowKeys, page: pagination.current, count: selectedRowKeys.length }).then((res) => {
            if (res.data.code == 200) {
                custom_search({ searchKey: '' }).then((res) => {
                    // console.log(res.data.list);
                    setData(res.data.list);
                    handleCancel1()
                    notification.success({ message: "设定成功！", placement: "top" })
                })
            }

        })
    };

    //分页
    const handleChange = (pagination: TablePaginationConfig) => {
        setPagination(pagination)//更新页码  //pagination 参数 包含有当前最新页码
        setLoading(true)
        //在这里发请求, 获取最新页码对应的数据
        custom_search({ searchKey: '', page: pagination.current, count: 10 }).then((res) => {
            setLoading(false);
            console.log(res.data)
            setData(res.data.list);//保存客户列表
        })
    }


    //选择发生改变的回调
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };


    //上传状态发生改变回调
    var handleUploadChange = (res: any) => {
        if (res.file.status == 'done' && res.file.response.code == 200) { //上传成功
            notification.success({ message: '上传成功!' });
        }
    }


    //删除单个客户
    var del = (record: any) => {
        console.log(record);
        custom_del({ id: record._id, searchKey: "" }).then((res) => {
            console.log(res.data);
            if (res.data.code == 200) {
                custom_search({ searchKey: '', page: 1, count: 10 }).then((res) => {
                    // console.log(res.data.list);
                    setData(res.data.list);
                    notification.success({ message: "删除成功！", placement: "top" })
                })
            }
        })
    }
    //删除多个客户
    var mdelete = () => {
        custom_delmany({ keys: selectedRowKeys, searchKey: "", page: pagination.current, count: selectedRowKeys.length }).then((res) => {
            console.log(res.data);
            if (res.data.code == 200) {
                custom_search({ searchKey: '' }).then((res) => {
                    // console.log(res.data.list);
                    setData(res.data.list);
                    notification.success({ message: "删除成功！", placement: "top" })
                })
            }
        })
    }

    //搜索
    const onSearch = (value: string) => {
        custom_search({ searchKey: value, page: 1, count: 10 }).then((res) => {
            // console.log(res.data.list);
            var arr = res.data.list.map((item: any) => {
                return {
                    name: item.name,
                    phone: item.phone,
                    email: item.email,
                    address: item.address,
                    leader: item.leader,
                    time: item.time,
                    key: item.key
                }
            })
            setData(arr)
        })
    }
    return (
        <div className='Custom_index'>
            <h4 style={{ marginBottom: "20px" }}>客户管理</h4>
            <div className="opet">
                <Search style={{ width: 300, marginRight: 20 }} placeholder="输入客户姓名" onSearch={onSearch} enterButton />
            </div>
            <div className='text'>
                <Space wrap>
                    <Button disabled={selectedRowKeys.length == 0}>创建人工外呼</Button>
                    <Button disabled={selectedRowKeys.length == 0}>写入机器外呼</Button>
                    <Button disabled={selectedRowKeys.length == 0}>发送消息</Button>
                    <Button disabled={selectedRowKeys.length == 0} onClick={() => { editleader() }}>设定负责人</Button>
                    <Button disabled={selectedRowKeys.length == 0} style={{ width: "50px" }}> <DeleteOutlined style={{ marginLeft: "0" }} onClick={() => { mdelete() }} /></Button>
                </Space>
                <div>
                    <Space wrap>
                        <Upload accept=".xls,.xlsx" action="/api/custom/import" name="excel" onChange={handleUploadChange} showUploadList={false}>
                            <Button type='primary'>导入客户</Button>
                        </Upload>
                        <Button type="primary" href="/api/custom/export">导出客户</Button>
                    </Space>
                </div>
            </div>
            {/* 表格组件 */}
            {/* columns 表格每一列如何渲染 */}
            {/* dataSource 表格的数据源 */}
            <Table columns={columns}
                loading={loading}
                size='middle'
                dataSource={data}
                pagination={pagination}
                rowSelection={rowSelection}
                onChange={handleChange}
            />
            <Modal title="设定负责人" open={isModalOpen1} onCancel={handleCancel1} >
                <Form
                    name="basic"
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    onFinish={onFinish}
                    form={form}
                >
                    <Form.Item
                        label="负责人"
                        name="leader"
                        rules={[{
                            required: true,
                            message: '请输入负责人',
                        }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
                        <Button type="primary" htmlType="submit">设定负责人</Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
}

export default Custom_index;